import { useI18n } from 'vue-i18n'

/**
 * 语言切换工具函数
 */
export const useLanguage = () => {
  const { locale } = useI18n()
  
  /**
   * 切换语言
   * @param {string} lang - 语言代码 ('zh' | 'en')
   */
  const changeLanguage = (lang) => {
    if (['zh', 'en'].includes(lang)) {
      locale.value = lang
      localStorage.setItem('lang', lang)
    }
  }
  
  /**
   * 获取当前语言
   * @returns {string} 当前语言代码
   */
  const getCurrentLanguage = () => {
    return locale.value
  }
  
  /**
   * 获取语言显示名称
   * @param {string} lang - 语言代码
   * @returns {string} 语言显示名称
   */
  const getLanguageName = (lang) => {
    const languageNames = {
      zh: '中文',
      en: 'English'
    }
    return languageNames[lang] || lang
  }
  
  /**
   * 初始化语言设置
   */
  const initLanguage = () => {
    const savedLang = localStorage.getItem('lang')
    if (savedLang && ['zh', 'en'].includes(savedLang)) {
      locale.value = savedLang
    } else {
      // 根据浏览器语言自动设置
      const browserLang = navigator.language.toLowerCase()
      if (browserLang.startsWith('zh')) {
        locale.value = 'zh'
      } else {
        locale.value = 'en'
      }
      localStorage.setItem('lang', locale.value)
    }
  }
  
  return {
    changeLanguage,
    getCurrentLanguage,
    getLanguageName,
    initLanguage
  }
}

/**
 * 语言切换组件
 */
export const LanguageSwitch = {
  name: 'LanguageSwitch',
  setup() {
    const { changeLanguage, getCurrentLanguage, getLanguageName } = useLanguage()
    
    const handleLanguageChange = (lang) => {
      changeLanguage(lang)
    }
    
    return {
      currentLang: getCurrentLanguage(),
      getLanguageName,
      handleLanguageChange
    }
  },
  template: `
    <el-dropdown @command="handleLanguageChange">
      <span class="language-switch">
        {{ getLanguageName(currentLang) }}
        <i class="el-icon-arrow-down el-icon--right"></i>
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item command="zh">中文</el-dropdown-item>
          <el-dropdown-item command="en">English</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  `
} 